package com.example.webexcel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.example.webexcel.common.Result;
import com.example.webexcel.domain.Student;
import com.example.webexcel.listener.DataListener;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {

    @PostMapping("/upload")
    public Result<Boolean> readExcel(MultipartFile uploadExcel) {
        try {
            //EasyExcel为入口
            //EasyExcel.read()参数为：1.读取文件的文件名(inputStream)，2.提取出来的类型，3.数据监听器
            ExcelReaderBuilder readerBuilder = EasyExcel.read(uploadExcel.getInputStream(), Student.class, new DataListener());
            //readerBuilder.sheet()参数为：1.sheet的序号(推荐)，2.sheet的名字(不推荐)，3.不写默认第一个
            ExcelReaderSheetBuilder sheet = readerBuilder.sheet();
            //得到sheet调用doRead函数
            sheet.doRead();
            //返回成功数据类型响应
            return new Result<>(1, true, "success");
        } catch (IOException e) {
            throw new RuntimeException(e);
            //...
            //返回失败数据类型响应
        }
    }

    // 生成一些数据 模拟
    private List<Student> initData() {
        List<Student> students = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            Student student = new Student();
            student.setStuId("123" + i);
            student.setStuName("yyf" + i);
            student.setStuSex("女");
            student.setBirthday(new Date());
            students.add(student);
        }
        return students;
    }

    @GetMapping("/download")
    public Result<Boolean> writeExcel(HttpServletResponse response) throws IOException {
        //mock些数据
        List<Student> students = initData();

        //固定设置返回头，复制粘贴即可
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("学生信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");


        ExcelWriterBuilder writeBuilder = EasyExcel.write(response.getOutputStream(), Student.class);
        ExcelWriterSheetBuilder sheet = writeBuilder.sheet();
        sheet.doWrite(students);

        return new Result<>(1, true, "success");
    }
}
